import chalk from 'chalk';
import ejs from 'ejs';
import fs from 'fs';
import path from 'path';

function getAllBiz(source) {
  if (!fs.existsSync(source)) {
    console.info(chalk.yellow(`目录不存在${source}`));

    return [];
  }

  const folders = fs
    .readdirSync(source, {
      withFileTypes: true,
      recursive: false,
    })
    .filter((el) => el.isDirectory())
    .map((el) => {
      let route = null;

      try {
        fs.statSync(`${source}\\${el.name}\\routes.js`);
        route = el.name;
      } catch (error) {
        // 若不存在则会抛出错误
      }

      return route;
    })
    .filter(Boolean);

  const bizList = [];

  folders.forEach((item) => {
    const itemPath = path.resolve(import.meta.dirname, `../src/pages/${item}/routes.js`);
    const name = item.replace(/-(\w)/g, (match, group1) => group1.toUpperCase());

    bizList.push({
      name: name,
      relativePath: `@/pages/${item}/routes.js`,
      path: itemPath,
    });
  });

  return bizList;
}

const targetFile = path.resolve(import.meta.dirname, '../src/routes/routes.js');
const bizPath = path.resolve(import.meta.dirname, '../src/pages');
const templatePath = path.resolve(import.meta.dirname, './biz-stage-config.ts.js');

console.info(chalk.green(`配置插件...`));

const template = fs.readFileSync(templatePath, 'utf8');
const bizList = getAllBiz(bizPath);
const result = ejs.render(template.replace(/`/g, ''), { plugins: bizList }, null);

fs.writeFile(targetFile, result, {}, (err) => {
  if (err) {
    console.error('write file error', err);
  } else {
    console.info(chalk.green(`配置插件完成: ${targetFile}\n`));
  }
});
